<template>
  <view class="home-container">
    <!-- 顶部标题栏 -->
    <view class="page-header">
      <view class="header-title">首页</view>
    </view>

    <!-- 功能入口 -->
    <view class="function-section">
      <view class="function-card" @click="handleGoToMall">
        <view class="function-icon mall-icon">
          <image class="icon-img" src="/static/images/mall-icon.png" mode="aspectFit"></image>
        </view>
        <view class="function-text">
          <view class="function-title">商城购物</view>
          <view class="function-desc">购买商品，享受优惠</view>
        </view>
        <view class="arrow">></view>
      </view>

      <view class="function-card" @click="handleCreateOrder">
        <view class="function-icon order-icon">
          <image class="icon-img" src="/static/images/order-icon.png" mode="aspectFit"></image>
        </view>
        <view class="function-text">
          <view class="function-title">创建订单</view>
          <view class="function-desc">发布其他类型订单</view>
        </view>
        <view class="arrow">></view>
      </view>
    </view>

    <!-- 商城内容区 -->
    <view class="mall-content" v-if="showMall">
      <!-- 搜索栏 -->
      <view class="search-bar">
        <input 
          class="search-input" 
          placeholder="搜索商品..." 
          v-model="productSearchKeyword"
          @confirm="handleSearchProducts"
        />
        <button class="search-btn" @click="handleSearchProducts">搜索</button>
      </view>

      <!-- 商品分类 -->
      <scroll-view 
        class="category-scroll" 
        scroll-x 
        show-scrollbar="false"
      >
        <view class="categories">
          <view 
            class="category-item" 
            :class="{ active: activeProductCategory === category.id }"
            v-for="category in productCategories" 
            :key="category.id"
            @click="() => handleSwitchProductCategory(category.id)"
          >
            {{ category.name }}
          </view>
        </view>
      </scroll-view>

      <!-- 商品列表 -->
      <view class="products-list">
        <view 
          class="product-item" 
          v-for="product in filteredProducts" 
          :key="product.id"
          @click="() => handleViewProductDetail(product.id)"
        >
          <image class="product-image" :src="product.image || '/static/images/product-default.jpg'" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{ product.name }}</view>
            <view class="product-description">{{ product.description }}</view>
            <view class="product-price">¥{{ formatPrice(product.price) }}</view>
            <button class="buy-btn" @click.stop="() => handleBuyProduct(product)">立即购买</button>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredProducts.length === 0 && !loading">
        <image class="empty-img" src="/static/empty/empty-product.png" mode="widthFix"></image>
        <view class="empty-text">暂无相关商品</view>
        <view class="empty-subtext">抱歉，没有找到您要的商品</view>
      </view>
      
      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <view class="loading-text">加载中...</view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getProductListAPI, getProductCategoryListAPI } from '@/api/product.js'

const router = useRouter?.() || {
  push: (options) => {
    const url = typeof options === 'string' 
      ? options 
      : `${options.path}?${new URLSearchParams(options.query).toString()}`
    uni.navigateTo({ url })
  }
}

// 是否显示商城内容
const showMall = ref(false)

// 商品搜索关键词
const productSearchKeyword = ref('')

// 当前激活的商品分类
const activeProductCategory = ref('all')

// 加载状态
const loading = ref(false)

// 商品分类
const productCategories = ref([
  { id: 'all', name: '全部' }
  // 其余分类将从后端动态加载
])

// 商品数据
const products = ref([])

// 根据分类和搜索关键词筛选商品
const filteredProducts = computed(() => {
  let result = products.value
  
  // 根据分类筛选
  if (activeProductCategory.value !== 'all') {
    result = result.filter(product => 
      String(product.category) === String(activeProductCategory.value)
    )
  }
  
  // 根据关键词搜索
  if (productSearchKeyword.value) {
    const keyword = productSearchKeyword.value.toLowerCase()
    result = result.filter(product => 
      product.name.toLowerCase().includes(keyword) || 
      product.description.toLowerCase().includes(keyword)
    )
  }
  
  return result
})

// 切换商品分类
const switchProductCategory = (categoryId) => {
  activeProductCategory.value = categoryId
}

// 搜索商品
const searchProducts = () => {
  loadProducts()
}

// 查看商品详情
const viewProductDetail = (productId) => {
  uni.showToast({
    title: '功能开发中...',
    icon: 'none'
  })
}

// 购买商品
const buyProduct = (product) => {
  uni.showModal({
    title: '确认购买',
    content: `确定要购买"${product.name}"吗？\n价格：¥${product.price ? product.price.toFixed(2) : '0.00'}`,
    confirmText: '确认购买',
    cancelText: '取消',
    confirmColor: '#1677ff',
    success: (res) => {
      if (res.confirm) {
        // 跳转到创建订单页面并传递商品信息
        uni.navigateTo({
          url: `/pages/create-order/create-order?product=${encodeURIComponent(JSON.stringify(product))}`
        })
      }
    }
  })
}

// 跳转到商城
const goToMall = () => {
  showMall.value = true
  // 加载商品数据
  loadProducts()
  // 加载商品分类
  loadProductCategories()
}

// 创建订单
const createOrder = () => {
  // 跳转到创建订单页面
  uni.navigateTo({
    url: '/pages/create-order/create-order'
  })
}

// 加载商品数据
const loadProducts = async () => {
  try {
    loading.value = true
    // 调用商品列表接口
    // 修改参数结构以适配后端接口要求
    const params = {
      pageSize: 100,
      current: 1
    };
    
    // 如果有搜索关键词，则添加到参数中
    if (productSearchKeyword.value) {
      params.keyword = productSearchKeyword.value;
    }
    
    console.log('请求参数:', params); // 调试信息
    
    const res = await getProductListAPI(params)
    
    console.log('商品接口返回数据:', res); // 调试信息
    
    if (res && res.code === 0) {
      // 处理商品数据，适配 product_info 表结构
      // 检查不同的可能字段名
      const rawData = res.data?.list || res.data?.records || [];
      console.log('原始商品数据:', rawData); // 调试信息
      
      products.value = rawData.map(item => {
        // 确保价格字段正确解析
        let price = 0;
        if (item.price !== undefined && item.price !== null) {
          price = parseFloat(item.price);
        } else if (item.productPrice !== undefined && item.productPrice !== null) {
          price = parseFloat(item.productPrice);
        }
        
        // 如果解析结果不是有效数字，则设置为0
        if (isNaN(price)) {
          price = 0;
        }
        
        // 为每个商品字段提供多种可能的字段名
        const product = {
          id: item.id || item.productId || null,
          name: item.productName || item.name || item.title || '未知商品',
          description: item.description || item.productDescription || item.desc || '暂无描述',
          price: price,
          category: item.categoryId || item.category || item.productCategory || 'other',
          image: item.image || item.productImage || item.pic || '/static/images/product-default.jpg',
          status: (item.status !== undefined) ? (parseInt(item.status) || 0) : 1, // 默认在售
          stock: parseInt(item.stock) || parseInt(item.quantity) || 0
        };
        
        console.log('单个商品映射结果:', product); // 调试信息
        return product;
      }).filter(item => {
        // 更宽松的过滤条件，如果status字段不存在或解析失败，默认显示
        const show = item.status !== 0 && item.id; // 只过滤明确下架的商品和没有ID的商品
        console.log('商品过滤结果:', show, '商品:', item); // 调试信息
        return show;
      });
      
      console.log('最终处理后的商品数据:', products.value); // 调试信息
    } else {
      uni.showToast({
        title: '获取商品列表失败',
        icon: 'none'
      })
      console.error('获取商品列表失败:', res);
    }
  } catch (err) {
    console.error('获取商品列表异常:', err)
    uni.showToast({
      title: '获取商品列表异常',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 加载商品分类数据
const loadProductCategories = async () => {
  try {
    const res = await getProductCategoryListAPI({
      pageSize: 100,
      current: 1
    })
    
    console.log('商品分类接口返回数据:', res); // 调试信息
    
    if (res && res.code === 0) {
      // 处理商品分类数据
      const rawData = res.data?.list || res.data?.records || []
      console.log('原始分类数据:', rawData); // 调试信息
      
      const categories = rawData.map(item => ({
        id: item.id || item.categoryId || null,
        name: item.name || item.categoryName || '未知分类'
      })).filter(item => item.id) // 过滤掉没有ID的分类
      
      console.log('处理后的分类数据:', categories); // 调试信息
      
      // 将"全部"分类与后端分类合并
      productCategories.value = [
        { id: 'all', name: '全部' },
        ...categories
      ]
    } else {
      uni.showToast({
        title: '获取商品分类失败',
        icon: 'none'
      })
      console.error('获取商品分类失败:', res)
    }
  } catch (err) {
    console.error('获取商品分类异常:', err)
    uni.showToast({
      title: '获取商品分类异常',
      icon: 'none'
    })
  }
}

// 格式化价格显示
const formatPrice = (price) => {
  if (price === undefined || price === null || isNaN(price)) {
    return '0.00';
  }
  return parseFloat(price).toFixed(2);
}

// 页面加载时执行
onMounted(() => {
  // 可以在这里请求最新的商品和服务数据
})

// 事件处理函数
const handleGoToMall = () => {
  goToMall()
}

const handleCreateOrder = () => {
  createOrder()
}

const handleSearchProducts = () => {
  searchProducts()
}

const handleSwitchProductCategory = (categoryId) => {
  switchProductCategory(categoryId)
}

const handleViewProductDetail = (productId) => {
  viewProductDetail(productId)
}

const handleBuyProduct = (product) => {
  buyProduct(product)
}
</script>

<style scoped>
.home-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  font-size: 28rpx;
}

.page-header {
  padding: 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
  text-align: center;
}

.header-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.function-section {
  padding: 20rpx;
}

.function-card {
  display: flex;
  align-items: center;
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
}

.function-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.mall-icon {
  background-color: #e8f3ff;
}

.order-icon {
  background-color: #fff7e8;
}

.icon-img {
  width: 50rpx;
  height: 50rpx;
}

.function-text {
  flex: 1;
}

.function-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.function-desc {
  font-size: 24rpx;
  color: #999;
}

.arrow {
  font-size: 36rpx;
  color: #ccc;
}

.search-bar {
  display: flex;
  padding: 20rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  background-color: #f5f7fa;
  border-radius: 35rpx;
  font-size: 28rpx;
}

.search-btn {
  width: 120rpx;
  height: 70rpx;
  line-height: 70rpx;
  margin-left: 20rpx;
  background-color: #1677ff;
  color: #fff;
  border-radius: 35rpx;
  font-size: 28rpx;
}

.category-scroll {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
}

.categories {
  display: flex;
  padding: 0 20rpx;
}

.category-item {
  padding: 15rpx 30rpx;
  margin-right: 20rpx;
  background-color: #f5f7fa;
  border-radius: 40rpx;
  font-size: 26rpx;
  color: #666;
  white-space: nowrap;
}

.category-item.active {
  background-color: #1677ff;
  color: #fff;
}

.products-list {
  padding: 0 20rpx;
}

.product-item {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.03);
  display: flex;
}

.product-image {
  width: 200rpx;
  height: 200rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
  background-color: #f0f0f0;
}

.product-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 30rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.product-description {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
  flex: 1;
}

.product-price {
  font-size: 32rpx;
  color: #ff4d4f;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.buy-btn {
  align-self: flex-start;
  padding: 0 30rpx;
  height: 60rpx;
  line-height: 60rpx;
  background-color: #1677ff;
  color: #fff;
  border-radius: 30rpx;
  font-size: 24rpx;
}

.empty-state {
  padding: 100rpx 20rpx;
  text-align: center;
}

.empty-img {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 30rpx;
  color: #666;
  margin-bottom: 15rpx;
}

.empty-subtext {
  font-size: 24rpx;
  color: #999;
}

.loading-state {
  padding: 40rpx;
  text-align: center;
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}
</style>